package com.example;

import cn.hutool.json.JSONUtil;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.oauth2.client.OAuth2AuthorizedClient;
import org.springframework.security.oauth2.client.annotation.RegisteredOAuth2AuthorizedClient;
import org.springframework.security.oauth2.core.OAuth2AccessToken;
import org.springframework.security.oauth2.core.OAuth2RefreshToken;
import org.springframework.security.oauth2.core.user.OAuth2User;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;

@Controller
public class OAuth2LoginDemoController {

    @GetMapping("/home")
    public String index(Model model,
                        @RegisteredOAuth2AuthorizedClient OAuth2AuthorizedClient authorizedClient,
                        @AuthenticationPrincipal OAuth2User oauth2User) {

        // 格式化后的JSON，即显示出带缩进的JSON
        String jsonPrettyStr = JSONUtil.toJsonPrettyStr(authorizedClient);
        System.out.println("jsonPrettySt: r" + jsonPrettyStr);

        OAuth2AccessToken accessToken = authorizedClient.getAccessToken();
        System.out.println("accessToken: " + accessToken);
        OAuth2RefreshToken refreshToken = authorizedClient.getRefreshToken();
        System.out.println("refreshToken: " + refreshToken);

        String jsonPretty = JSONUtil.toJsonPrettyStr(oauth2User);
        System.out.println("jsonPretty: " + jsonPretty);

        model.addAttribute("userName", oauth2User.getName());
        model.addAttribute("clientName", authorizedClient.getClientRegistration().getClientName());
        model.addAttribute("userAttributes", oauth2User.getAttributes());
        return "index";
    }
}
